<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 用户优惠券管理
 */
namespace app\ais\model;
use think\Model;

class AisCouponUser extends Model{


    /**
     * 好店
     * @return void
     */
    public function store(){
        return $this->hasOne('AisStore','id','store_id');
    }

    /**
     * 用户
     * @return void
     */
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    } 
    
    /**
     * 优惠券
     * @return void
     */
    public function coupon(){
        return $this->hasOne('AisCoupon','id','coupon_id');
    }

    /**
     * 批量添加优惠券
     * @param array $ids  优惠券的ID
     * @param integer $uid  用户ID
     * @return void
     */
    public static function addUserCoupon($ids,int $uid){
        $ids = json_decode($ids,true);
        if(empty($ids)){
            return;
        }
        $coupon = new AisCoupon();
        $lists = $coupon->where(['id' => $ids])->select();
        if(empty($lists)){
            return;
        }
        $data = [];
        foreach ($lists as $key => $value) {
            $data[$key]['member_miniapp_id'] = $value['member_miniapp_id'];
            $data[$key]['store_id']          = $value['store_id'];
            $data[$key]['coupon_id']         = $value['id'];
            $data[$key]['uid']               = $uid;
            $data[$key]['parent_store_id']   = 0;
            $data[$key]['is_end']            = 0;
            $data[$key]['types']             = $value['types'];
            $data[$key]['name']              = $value['name'];
            $data[$key]['price']             = $value['price'];
            $data[$key]['amount']            = $value['amount'];
            $data[$key]['discount']          = $value['discount'];
            $data[$key]['howmuch']           = $value['howmuch'];
            $data[$key]['tips']              = $value['tips'];
            $data[$key]['update_time']       = time();
            $data[$key]['create_time']       = time();
        }
        return self::insertAll($data);
    }
}